package Airport;

public class Airport {

	private Flight[] flights;
	public Flight[] getFlights() {
		return flights;
	}

	
	public Airport(int flightsCount) {
		
		super();
		
		if (flightsCount < 0) flightsCount = 0;
		flights = new Flight[flightsCount];
	}
	
	
	public void newFlight(int seats) {
		
		int freePlace = getFreePlaceForFlight();
		if (freePlace >= 0) {
			flights[freePlace] = new Flight(freePlace,seats);
		} else {
			System.out.println("Can't add flight");
		}
	}
	public void removeFlight(int id) {
		
		if (getFlightWithID(id) != null) {
			
			flights[id] = null;
		} else {
			System.out.println("Can't remove flight");
		}
	}
	
	
	public void cancelFlight(int id) {
		
		Flight flight = getFlightWithID(id);
		if (flight != null) {
			FlightController.cancelFlightInArray(flight, flights);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	public void openFlight(int id) {
		
		Flight flight = getFlightWithID(id);
		if (flight != null) {
			FlightController.openFlightInArray(flight, flights);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	public void delayFlight(int id) {
		
		Flight flight = getFlightWithID(id);
		if (flight != null) {
			FlightController.delayFlightInArray(flight, flights);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	
	
	public void addPassenger(int id, Passenger passenger) {
		
		Flight flight = getFlightWithID(id);
		if (flight != null) {
			flight.addPassenger(passenger);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	public void removePassenger(int id, Passenger passenger) {
		
		Flight flight = getFlightWithID(id);
		if (flight != null) {
			flight.removePassenger(passenger);
		} else {
			System.out.println("This flight does not exist.");
		}
	}
	
	private int getFreePlaceForFlight() {
		
		for (int i=0; i<flights.length; i++) {
			if (flights[i] == null) return i;
		}
		return -1;
	}
	private Flight getFlightWithID(int id) {
		
		if (id >= 0 && id < flights.length) {
			return flights[id];
		}
		return null;
	}
	
	@Override
	public String toString() {
		
		StringBuilder strBld = new StringBuilder();
		for (Flight flight : flights) {
			if (flight != null)
				strBld.append(flight.toString() + "\n");
		}
		if (strBld.length() != 0)
			strBld.deleteCharAt(strBld.length()-1);
		
		return strBld.toString();
	}
	
}
